package com.digital.smartgrow.controller.sysinfo;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.digital.smartgrow.common.advice.Result;
import com.digital.smartgrow.dto.datacenter.DictionaryPageDTO;
import com.digital.smartgrow.entity.sysinfo.Dictionary;
import com.digital.smartgrow.service.sysinfo.DictionaryService;
import com.digital.smartgrow.vo.dict.DictVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by SunYuechao on 2022/7/11 下午8:04
 */
@Api(tags = "字典")
@RestController
@RequestMapping("${context.prefix}/syc/dict")
public class DictController {

    @Autowired
    private DictionaryService dictionaryService;

    @ApiOperation(value = "字典-分页查询")
    @PostMapping("/list")
    public Object getListByPage(@RequestBody DictionaryPageDTO dictionaryPageDTO){
        return dictionaryService.getListByPage(dictionaryPageDTO);
    }

    @ApiOperation(value = "字典-详情")
    @GetMapping("/{id}")
    public Object getInfo(@PathVariable Integer id){
        if (id == null) return "id不能为空";
        return dictionaryService.getInfo(id);
    }

    @ApiOperation(value = "字典-删除")
    @DeleteMapping("/{id}")
    public Object removeById(@PathVariable Integer id) {
        if (id == null) return Result.fail("id不能为空");
        Dictionary dictionary = dictionaryService.getById(id);
        if(dictionary.getIssys()==1){
            return Result.fail("系统默认，不允许删除");
        }
         return dictionaryService.removeAllById(id);
    }

    @ApiOperation(value = "字典-新增")
    @PostMapping()
    public Object add(@Valid @RequestBody DictVo dict) {
        try {
            return dictionaryService.saveAll(dict);
        } catch (Exception e) {
            return Result.fail("字典ID不允许重复");
        }
    }

    @ApiOperation(value = "字典-编辑")
    @PutMapping()
    public Object edit(@Valid @RequestBody DictVo dict) {

        if (dict == null || dict.getId() == null) return Result.fail("id不能为空");
        if(dict.getIssys()==1){
            return Result.fail("系统默认，不允许编辑");
        }
        //先删除，在添加
        //dictionaryService.removeAllById(dict.getId());
        return dictionaryService.updateAll(dict);
    }

    @ApiOperation(value = "字典-根据code查询数据项")
    @GetMapping("/code/{dictNumber}")
    public Object select(@PathVariable String dictNumber) {
        if (dictNumber == null || StringUtils.isBlank(dictNumber)) return Result.fail("参数不能为空");

        return dictionaryService.select(dictNumber);
    }


    @ApiOperation(value = "字典-根据ID及关键字查询code")
    @GetMapping("/key/{id}")
    public Object selectBykey(@PathVariable Integer id, @RequestParam(required = false)String keyword) {
        String dictNumber=dictionaryService.selectBykey(id,keyword);

        return dictNumber;
    }

}
